package com.zeedev.flyingsaucer.beers.activities.beerlists;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.zeedev.flyingsaucer.adapter.UntastedCursorAdapter;
import com.zeedev.flyingsaucer.beers.activities.beerdialog.BeerDialog2;
import com.zeedev.flyingsaucer.beers.activities.filter.FilterDialogActivity;
import com.zeedev.flyingsaucer.data.BeerFilter;
import com.zeedev.flyingsaucer.data.BeerUri;
import com.zeedev.flyingsaucer.modules.DownloadModule.interfaces.DownloadManager;
import com.zeedev.flyingsaucer.ufoclub.R;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv.Beers;
import mobi.zeedev.flyingsaucer.common.DataModule.MetaBeer;
import mobi.zeedev.flyingsaucer.common.DataModule.Util;
import roboguice.activity.RoboListActivity;

public class BeerList extends RoboListActivity {

    private static final int FILTER_DIALOG_ACTIVITY = 0;

    private Cursor mCursor;
    private UntastedCursorAdapter mAdapter;

    @Inject
    DownloadManager downloadManager;

    @Inject
    LocalListModel lm;

    @Inject
    Injector injector;

    @Inject
    Provider<BeerUri> defaultBeerUri;

    @Inject
    Provider<Cursor> mCursorProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        mCursor = mCursorProvider.get();
        mAdapter = new UntastedCursorAdapter(this, R.layout.beer_indicator_flat, mCursor, true);
        setListAdapter(mAdapter);
        getListView().setFastScrollEnabled(true);

    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Menu
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.untasted, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            //STYLE
            case R.id.untasted_submenu_filter_style: {
                //TODO fix this
                startFilterDialog(Beers.STYLE_NAME);
                return true;
            }

            case R.id.untasted_submenu_filter_country: {
                //TODO fix this
                startFilterDialog(Beers.COUNTRY_NAME);
                return true;
            }

            case R.id.untasted_submenu_filter_brewer: {
                //TODO fix this
                startFilterDialog(Beers.BREWER_NAME);
                return true;
            }

            //CONTAINER
            case R.id.untasted_submenu_filter_container: {
                //Object m = this.findViewById(R.id.untasted_submenu_filter_container_childmenu);

                //MenuItem mi = (MenuItem) this.findViewById(R.id.container_submenu_group);
                //m.performIdentifierAction(R.id.container_submenu_group, 0); //Menu.FLAG_PERFORM_NO_CLOSE
                //Log.d(TAG, "Menu type: " + m.getClass().getCanonicalName());
                //AlertDialog ad = new AlertDialog();
                showDialog(0);
                return true;
            }
/*            case R.id.draught_filter: {
            	//this.containerFilterType = FilterType.DRAUGHT;
            	mFilter.setContainerType(ContainerType.DRAUGHT);
            	update_ListView(ContainerType.DRAUGHT);
            	
            	return true;
            }
            case R.id.bottled_filter: {
            	mFilter.setContainerType(ContainerType.BOTTLED);
            	update_ListView(ContainerType.BOTTLED);
            	return true;
            }
            case R.id.all_container_filter: {
            	mFilter.setContainerType(ContainerType.ALL);
            	update_ListView(ContainerType.ALL);
            	return true;
            }*/

            //REFRESH
            case R.id.menu_tasted_refresh: {
//            	BeerTabActivity bta = (BeerTabActivity) this.getParent();
//            	bta.startLookup();
//            	BeerListParent bta = (BeerListParent) this.getParent();
//            	try {
//            		Object controller = this.getParent().getClass().getDeclaredField("controller").get(this.getParent());
//            		controller.getClass().getMethod("init", (Class[]) null).invoke(controller, null);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
                downloadManager.startRefresh();
//            	bta.controller.init();
                return true;
            }
            //RESET
            case R.id.untasted_submenu_filter_reset: {
                //this.containerFilterType = FilterType.ALL;
//            	mFilter = new BeerFilter().setContainerType(ContainerType.ALL);
                //if (stylesFilter = null) {
                //stylesFilter = null;
                //}
                lm.setBeerUri(defaultBeerUri.get());
                update_ListView();
                return true;
            }
            default: {
                return true;
            }

        }

    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        //TODO fix this
        if (true) {//app.hasLoadedExtraBeerInfo()
            //menu.setGroupEnabled(R.id.container_submenu_disable, true);
            menu.findItem(R.id.untasted_submenu_filter_style).setEnabled(true);
            menu.findItem(R.id.untasted_submenu_filter_brewer).setEnabled(true);
            menu.findItem(R.id.untasted_submenu_filter_country).setEnabled(true);
        } else {
//			menu.setGroupEnabled(R.id.container_submenu_disable, false);
            //menu.findItem(R.id.container_submenu_disable).setEnabled(false);
            menu.findItem(R.id.untasted_submenu_filter_style).setEnabled(false);
            menu.findItem(R.id.untasted_submenu_filter_brewer).setEnabled(false);
            menu.findItem(R.id.untasted_submenu_filter_country).setEnabled(false);
        }
//		menu.findItem(R.id.container_submenu_disable).set
        return super.onPrepareOptionsMenu(menu);
    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Filter Container Dialog
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Override
    protected Dialog onCreateDialog(int id) {


        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setSingleChoiceItems(new String[]{"All", "Bottled", "Draught"}, 0, containerOnClickListener);
        return b.create();

    }

    private OnClickListener containerOnClickListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:
                    lm.getBeerUri().getGroupedSelectionSet(Beers.CONTAINER).clear();
                    update_ListView();
                    dialog.dismiss();
                    break;
                case 1:
                    lm.getBeerUri().getGroupedSelectionSet(Beers.CONTAINER).clear();
                    lm.getBeerUri().getGroupedSelectionSet(Beers.CONTAINER).add("bottled");
                    update_ListView();
                    dialog.dismiss();
                    break;
                case 2:
                    lm.getBeerUri().getGroupedSelectionSet(Beers.CONTAINER).clear();
                    lm.getBeerUri().getGroupedSelectionSet(Beers.CONTAINER).add("draught");
                    update_ListView();
                    dialog.dismiss();
                    break;
            }

        }
    };

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
//        AlertDialog ad = (AlertDialog) dialog;
        //Object otest = ad.findViewById(android.R.layout.simple_list_item_single_choice);

//		switch (mFilter.getContainerType()) {
//		case ALL:
//			//UntastedActivity.this.containerFilterType = FilterType.ALL;
//			//update_ListView();
//			//ad.getListView().setSelection(0);
//			ad.getListView().setItemChecked(0, true);
//			break;
//		case BOTTLED:
//			//UntastedActivity.this.containerFilterType = FilterType.BOTTLED;
//			//update_ListView();
//			//ad.getListView().setSelection(1);
//			ad.getListView().setItemChecked(1, true);
//			break;
//		case DRAUGHT:
//			//UntastedActivity.this.containerFilterType = FilterType.DRAUGHT;
//			//update_ListView();
//			//ad.getListView().setSelection(2);
//			ad.getListView().setItemChecked(2, true);
//			break;
//		}

        //ad.getListView().setSelection(position)

        super.onPrepareDialog(id, dialog);
    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Business Logic
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    private void startFilterDialog(String propertyIn) {
        Intent tIntent = new Intent(this, FilterDialogActivity.class);
//    	BeerFilterProvider bf = new BeerFilterProvider(propertyIn, MemberBeer.FILTER_CONTENT_URI);

//    	if (this.controller. == )
        lm.getBeerUri().groupBy = propertyIn;
        lm.getBeerUri().sortBy = propertyIn + " asc";
        tIntent.putExtra(BeerFilter.BEER_FILTER, lm.getBeerUri());
        this.startActivityForResult(tIntent, FILTER_DIALOG_ACTIVITY);
    }


/*    @Inject
    @Named("currentCursor")
    Provider<Cursor> currentBeerUriCursorProvider;*/

    public void update_ListView() {
//		lm.setBeerUri(mFilter2);

        //TODO FIX THIS
        mAdapter.setFilterQueryProvider(new FilterQueryProvider() {

            @Override
            public Cursor runQuery(CharSequence constraint) {
//				mFilter2.getBeerFilter().setContainerType(ContainerType.BOTTLED);
//				mFilter2.getBeerFilter().setTastedType(TastedType.NOT_TASTED);

                lm.getBeerUri().sortBy = Beers.NAME + " asc";
                lm.getBeerUri().groupBy = null;

                Cursor c = managedQuery(lm.getBeerUri().getUri(FlyingSaucerConv.Members.MemberBeer.FILTER_CONTENT_URI), Util.asArNonReduce(FlyingSaucerConv.Members.MemberBeer.STANDARD_COLUMNS, FlyingSaucerConv.Members.MemberBeer.MEMBER_BEER_KEY), null, null, null);
//                Cursor c = currentBeerUriCursorProvider.get();

                return c;
            }
        });

//		mAdapter.runQueryOnBackgroundThread("");

        mAdapter.getFilter().filter("");


//        lm.getBeerUri().sortBy = Beers.NAME + " asc";
//        lm.getBeerUri().groupBy = null;
//        mAdapter.changeCursor(currentBeerUriCursorProvider.get());


//        mAdapter.notifyDataSetChanged();

//		mAdapter.getCursor().requery();
//		mAdapter.changeCursor(managedQuery( mFilter.getUri() , Util.asArNonReduce(MemberBeer.STANDARD_COLUMNS, Members.MemberBeer.IS_TASTED, Members.MemberBeer.ACTIVE), null, null, null));


//		if (mCursor!=null) {
//			mCursor.close();	
//		}
//		
//		mFilter.getCommandList().clear();
//		
//		Cursor tCursor = model.db().getGroupCursor2(mFilter, null, MetaBeer.NAME);
//		
//		if (tCursor.getCount() >= 1) {
//		} else {
//			tCursor.close();
//			if (model.db().isEmpty()) {
//				return;
//			}
//			
//			Toast.makeText(this, "Selected filter properties returned no results.", Toast.LENGTH_SHORT).show();
//
//			if (lastSelection != null) {
//				if (lastSelection.equals(ContainerType.class.getName())) {
//					mFilter.setContainerType(ContainerType.ALL);
//				} else {
//					mFilter.getPropertySelectionValuesMap().remove(lastSelection);
//				}
//			}
//			
//			tCursor = model.db().getGroupCursor2(mFilter, null, MetaBeer.NAME);		
//		}
//		
//
//		mCursor = tCursor;
//		this.startManagingCursor(tCursor);
//		mAdapter.changeCursor(tCursor);

//		mCursor.

    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Callbacks
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Cursor o = (Cursor) this.getListView().getItemAtPosition(position);
        //Beer h = new Beer();
        //h.setRawName(o.getString(o.getColumnIndex(MetaBeer.NAME)));
        //h.setDescription(o.getString(o.getColumnIndex(MetaBeer.DESCRIPTION)));

        //selectedBeer = h;
        //this.showDialog(BeerNotTastedTastedActivity.DIALOG_BEER);
        Integer beerId = o.getInt(o.getColumnIndex(MetaBeer.BEER_ID));


        //Intent dialogIntent = new Intent(this, BeerDialog.class);
        //dialogIntent.putExtra(MetaBeer.BEER_ID, beerId);
        //this.startActivity(dialogIntent);
//		if (beerId == null) {
//			beerId = 1;
//		}
        Intent dialogIntent = BeerDialog2.makeDialog(this, beerId);
        this.startActivityForResult(dialogIntent, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

//        super.onActivityResult(requestCode, resultCode, data);

//		Log.d(TAG,"On Activity Result: " + requestCode + " " + resultCode + " " + data);


        if (requestCode == FILTER_DIALOG_ACTIVITY) {
            if (data != null) {
                if (data.hasExtra(BeerFilter.BEER_FILTER)) {
                    //mFilter.attain( (BeerFilter) data.getSerializableExtra(BeerFilter.BEER_FILTER) );
                    // = (BeerFilterProvider) data.getParcelableExtra(BeerFilter.BEER_FILTER);
                    BeerUri curBeerUri = (BeerUri) data.getSerializableExtra(BeerFilter.BEER_FILTER);

                    lm.setBeerUri(curBeerUri);
//					String lastSelection  = data.getStringExtra(FilterDialogActivity.METABEER_GROUP_BY);
//					String lastSelection = mFilter.getGroupBy();
//                    BeerList.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
                    update_ListView();
//                        }
//                    });

                }
            }
        }


    }


}
